import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> ret = new ArrayList<>();
        Queue<Node> queue = new LinkedList<>();
        int size = 0; // 记录每一层的结点个数
        queue.offer(root);
        while (!queue.isEmpty()) {
            size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size -- != 0) { // 循环size次，将节点的子节点全部入队
                Node cur = queue.poll();
                list.add(cur.val);
                int n = cur.children.size();
                for (int i = 0; i < n; i++) {
                    queue.offer(cur.children.remove(0));
                }
            }
            ret.add(list);
        }
        return ret;
    }
}